package com.minglv.mini.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dtflys.forest.http.ForestResponse;
import com.minglv.mini.apiclient.WxClient;
import com.minglv.mini.domain.User;
import com.minglv.mini.mapper.UserMapper;
import com.minglv.mini.tools.MiniProgramConstants;
import com.ruoyi.common.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Slf4j
//@DataSource(DataSourceType.SLAVE)
public class MiniProgramLoginSerivce {


    @Resource
    WxClient wxLoginClient;

    @Resource
    UserMapper userMapper;

    public Map miniLogin(Map param){

        Map<String,Object> re = new HashMap<>();
        Map<String,Object> query = new HashMap<>();
        query.put("appid", MiniProgramConstants.MINI_APPID);
        query.put("secret",MiniProgramConstants.MINI_SECRET);
        query.put("js_code",param.get("code").toString());
        query.put("grant_type","authorization_code");
        ForestResponse<Map> mapForestResponse = wxLoginClient.jscode2session(query);
        if (mapForestResponse.statusOk()) {
            Map result = mapForestResponse.getResult();

            User user = userMapper.getUserByOpenid(result.get("openid").toString());

            if (ObjectUtils.isEmpty(user)) {
                Long maxId = userMapper.getMaxId();
                user = new User();
                user.setId(maxId + 1);
                user.setOpenid(result.get("openid").toString());
                user.setUserLevel(1L);
                user.setCheese(BigDecimal.ZERO);
                user.setIntegral(BigDecimal.ZERO);
                user.setIsAdmin(0);
                user.setSort(0l);
                user.setStatus(1);
                if (ObjectUtils.isNotEmpty(param.get("userInfo"))) {
                    LinkedHashMap userInfo = (LinkedHashMap) param.get("userInfo");
                    user.setAvatar(userInfo.get("avatarUrl").toString());
                    user.setNickname(userInfo.get("nickName").toString());
                }
                userMapper.insertUser(user);
            }

            Calendar instance = Calendar.getInstance();
            if ("oWY6i6-7PrVa2hdcNhc2EQPvAuZw".equals(result.get("openid").toString())) {
                instance.add(Calendar.MINUTE, 5);
            } else {
                instance.add(Calendar.HOUR, 12);
            }

            Map<String, Object> map = new HashMap<>();
            String token = JWT.create()
                    .withHeader(map)//添加头部
                    .withClaim("openid",result.get("openid").toString())//添加payload
                    .withClaim("nickName",user.getNickname())
                    .withClaim("id",user.getId())
//                    .withClaim("email",userDB.getEmail())
                    .withExpiresAt(instance.getTime())//设置过期时间
                    .sign(Algorithm.HMAC256(MiniProgramConstants.JWT_SECRET));//设置签名 密钥

            re.put("access_token", Constants.TOKEN_PREFIX + token);
            re.put("expires_in","30");
            re.put("info",user);

        }
        return re;
    }



}
